import { take, all, takeEvery, delay, call, put, apply, select, cps } from 'redux-saga/effects'
import { actionTypes, fetchStudents2, createLoadingAction, createStudentAction } from '../action/student/searchResult'

function getData() {
    return new Promise((resolve, reject) => { setTimeout(() => resolve([{ name: 'sss' }]), 1000) })
}

function func(...args) {
    console.log(this)
    console.log(args) // [1,2,3]
    return 5
}

function mockData(callback) {
    setTimeout(() => {
        if (Math.random() > 0.5) {
            // nodejs 风格
            callback(null, [{ name: 'sss' }])
        } else {
            callback(new Error('出错了！！！'), null)
        }
    }, 1000)
}

function* student() {
    // yield put(createLoadingAction(true))

    // const data = yield getData()
    // saga 发现返回的是一个promise，会等待promise完成 
    // 如果promise状态变为 rejected,saga会使用 generator.throw抛出错误，可以用trycatch捕获

    // 使用call指令 (函数，参数)
    // const data = yield call(getData)

    // 使用apply
    // const data = yield apply(null, getData, [])

    // yield put(createStudentAction({ students: data, total: data.length }))
    // yield put(createLoadingAction(false))

    // const state = yield select()
    // console.log(state);

    // const res = yield call([{ name: 'this指向' }, func], 1, 2, 3);
    // console.log(res);


    const data = yield cps(mockData)
    console.log(data);
}

// 尽量在 yield 后面使用指令

export default function* () {
    yield takeEvery(actionTypes.fetchStudents, student)
    console.log('正在监听fetchStudents');
}